package org.carpediem.conman.server; /**
 * @author Mark Petrovic
 */

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class ServerListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    private final Logger logger = Logger.getLogger(ServerListener.class.getName());
    private final static String PERSISTER = "s3Persister";

    public ServerListener() {
    }

    public void contextInitialized(ServletContextEvent sce) {
        //initLogging();
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("springconfig.xml");
        sce.getServletContext().setAttribute("springContext", applicationContext);
        sce.getServletContext().setAttribute(PERSISTER, applicationContext.getBean(PERSISTER));
    }

    public void contextDestroyed(ServletContextEvent sce) {
        S3Persister persister = (S3Persister) sce.getServletContext().getAttribute(PERSISTER);
        persister.quit();
    }

    public void sessionCreated(HttpSessionEvent se) {
    }

    public void sessionDestroyed(HttpSessionEvent se) {
    }

    public void attributeAdded(HttpSessionBindingEvent sbe) {
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
    }

    private void initLogging() {
        try {
            new File("logs").mkdirs();
            ClassLoader cl = this.getClass().getClassLoader();
            InputStream is = cl.getResourceAsStream("logging.properties");
            LogManager logManager = LogManager.getLogManager();
            logManager.readConfiguration(is);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}
